package controllers
{
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.text.StyleSheet;
	
	import models.PrettyCodeStyle;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;
	
	import net.anirudh.as3syntaxhighlight.CodePrettyPrint;
	
	public class SourceController extends Object
	{
		public var sourceFile:File;
		
		// Source lines in string
		public var source:String = "";

		private var codeStyle:StyleSheet;
		private var prettyPrint:CodePrettyPrint;
		
		// Name of the source file
		[Bindable]
		public var fileName:String;

		public function SourceController()
		{
			super();
		}
		
		public function showLoadSourceWindow():void{
			var python:FileFilter = new FileFilter("Python Scripts (*.py)", "*.py");
			sourceFile = new File();
			sourceFile.addEventListener(Event.SELECT, onSourceFileSelected);
			sourceFile.browse([python]);
		}
		
		private function onSourceFileSelected(evt:Event):void{
			var stream:FileStream = new FileStream();
			stream.open(sourceFile, FileMode.READ);
			source = stream.readUTFBytes(stream.bytesAvailable);
			
			fileName = sourceFile.name;
			
			processSourceCode(source);
		}
		
		public function processSourceCode(source:String):void{
			// Highlight the code
			if(!codeStyle){
				codeStyle = new StyleSheet();
				prettyPrint = new CodePrettyPrint();
				codeStyle.parseCSS(PrettyCodeStyle.CSSString);
			}
			
			var formattedString:String = prettyPrint.prettyPrintOne(source, null, true);
			var lines:Array = formattedString.split("<br />");
			
			Application.application.mainView.sourceView.codeStyle = codeStyle;
			Application.application.mainView.sourceView.dataProvider = new ArrayCollection(lines);
			
			Application.application.debugMainView.debugSourceView.codeStyle = codeStyle;
			Application.application.debugMainView.debugSourceView.dataProvider = new ArrayCollection(lines);
		}
		
	}
}